<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    button{
      position: fixed;
      right: 50px;
      bottom: 50px;
      display: none;
    }
  </style>
</head>

<body style="height: 3000px;">
  <div id="app">
    <home></home>
  </div>
  <script src="./vue.js"></script>
  <script>
    Vue.directive('backtop', {
      inserted(el, binding){
        // 回到定义显示消失切换
        window.onscroll = () =>{
          // 滚动举例
          const sTop = document.documentElement.scrollTop || document.body.scrollTop;
          if(sTop > binding.value){
            el.style.display = 'block';
          }else{
            el.style.display = 'none';
          }
        }
        // 点击按钮回到顶部
        el.onclick = () => {
          window.scrollTo(0,0);
        }
      },
      unbind(){
        // 解绑时
        window.onscroll = null;
      }
    })
    const Home = {
      template: `
        <div>
          <h2>home组件</h2>
          <button v-backtop="200">回到顶部</button>
        </div>
      `
    }
    Vue.component('Home', Home)
    const vm = new Vue({
      el: '#app'
    })
  </script>
</body>

</html>